package com.jin.mqtt;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.util.Log;

public class NetworkStateMonitor {
    private final ConnectivityManager connectivityManager;
    private final ConnectivityManager.NetworkCallback networkCallback;
    private final NetworkStateListener listener;

    public interface NetworkStateListener {
        void onConnected();
        void onDisconnected();
    }

    public NetworkStateMonitor(Context context, NetworkStateListener listener) {
        this.connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        this.listener = listener;

        this.networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                Log.d("NetworkMonitor", "网络已连接");
                if (listener != null) listener.onConnected();
            }

            @Override
            public void onLost(Network network) {
                Log.e("NetworkMonitor", "网络断开");
                if (listener != null) listener.onDisconnected();
            }
        };
    }

    public void register() {
        NetworkRequest networkRequest = new NetworkRequest.Builder().build();
        connectivityManager.registerNetworkCallback(networkRequest, networkCallback);
    }

    public void unregister() {
        connectivityManager.unregisterNetworkCallback(networkCallback);
    }
}

